<template>
  <div class="no-background-container">
    <header-component />
    <div style="height: 60px"></div>

    <!-- 搜索表单 -->
    <search-form-qvil
      v-model="searchParams"
      :fields="searchFieldsWithOptions"
      :loading="tableState.loading"
      @reset="handleReset"
      @search="handleSearch"
    >
      <template #actions>
        <el-button type="primary" @click="handleAdd">新增{{ moduleName }}</el-button>
      </template>
    </search-form-qvil>

    <!-- 表格 -->
    <table-qvil
      v-model:page="page"
      v-model:page-size="pageSize"
      :border="true"
      :columns="tableState.visibleColumns"
      :data="tableState.data"
      :loading="tableState.loading"
      :show-index="true"
      :stripe="true"
      :total="tableState.pagination.total"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
      <!-- 会议室名称列 -->
      <template #column-roomName="{ row }">
        <div style="cursor: pointer" @click="handleDetails(row)">
          <div style="font-size: 14px; font-weight: 500; color: var(--el-color-primary)">
            {{ row.roomName }}
          </div>
          <div style="font-size: 12px">容量: {{ row.capacity }}人</div>
        </div>
      </template>

      <!-- 会议室位置列 -->
      <template #column-positionDescription="{ row }">
        <div style="font-size: 12px">位置: {{ row.positionDescription }}</div>
      </template>

      <!-- 设备配置列 -->
      <template #column-equipmentDisplay="{ row }">
        <div style="display: flex; flex-wrap: wrap; gap: 5px">
          <template v-if="getEquipmentTags(row).length > 0">
            <el-tag
              v-for="(item, index) in getEquipmentTags(row)"
              :key="index"
              effect="plain"
              size="small"
              :type="getEquipmentTagType(item)"
            >
              {{ item }}
            </el-tag>
          </template>
          <span v-else style="font-size: 13px; color: var(--el-text-color-secondary)">暂无设备配置</span>
        </div>
      </template>

      <!-- 审批状态列 -->
      <template #column-isApproval="{ row }">
        <el-tag effect="plain" :type="row.isApproval === '是' ? 'danger' : 'success'">
          {{ row.isApproval === '是' ? '需要审批' : '无需审批' }}
        </el-tag>
      </template>

      <!-- 会议室状态列 -->
      <template #column-openStatus="{ row }">
        <el-tag effect="plain" :type="getStatusTagType(row.openStatus || '')">
          {{ row.openStatus || '未设置' }}
        </el-tag>
      </template>

      <!-- 操作列 -->
      <template #column-operations="{ row }">
        <div class="operations-container">
          <el-button size="small" text type="primary" @click="handleEdit(row)">
            <el-icon class="button-icon"><edit-pen /></el-icon>
            编辑
          </el-button>
          <el-button size="small" text type="info" @click="handleDetails(row)">
            <el-icon class="button-icon"><view /></el-icon>
            详情
          </el-button>
          <el-button size="small" text type="danger" @click="handleDelete(row)">
            <el-icon class="button-icon"><delete /></el-icon>
            删除
          </el-button>
        </div>
      </template>
    </table-qvil>

    <!-- 详情弹窗 -->
    <detail-dialog-qvil
      v-model="detailDialogVisible"
      :detail-data="currentDetail || {}"
      :fields="detailFields"
      :loading="false"
      title="会议室详情"
      @close="handleDetailClose"
    />

    <!-- 表单弹窗 -->
    <form-dialog-qvil
      ref="formDialogRef"
      v-model="dialogState.visible"
      :confirm-loading="dialogState.confirmLoading"
      :error="dialogState.error"
      :fields="formFields"
      :form-data="dialogState.formData"
      :loading="dialogState.loading"
      :title="dialogState.title"
      @cancel="handleFormCancel"
      @confirm="handleFormSubmit"
      @validation-error="handleValidationError"
    />
  </div>
</template>

<script lang="ts" setup>
import { Delete, EditPen } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import HeaderComponent from '../components/header.vue'
import type { MeetingRoomExtended } from './config'
import { ROOM_STATUS, formFields, formatFormData, getEquipmentTags, moduleName, searchFields, tableColumns } from './config'
import { addApi, delApi, editApi, getListApi } from '/@/api/meetingRooms'
import type { MeetingRoom } from '/@/types/api'
import request from '/@/utils/request'

// 查询参数
const searchParams = ref({
  roomName: '',
  status: '',
  positionDescription: '',
})

// 查询表单
interface QueryForm {
  roomName: string
  status: string
  positionDescription: string
  page: number
  limit: number
}

const queryForm = ref<QueryForm>({
  roomName: '',
  status: '',
  positionDescription: '',
  page: 1,
  limit: 20,
})

// 表格状态
const tableState = reactive({
  data: [] as MeetingRoom[],
  loading: false,
  pagination: {
    total: 0,
  },
  visibleColumns: tableColumns,
})

// 分页参数
const page = ref(1)
const pageSize = ref(20)

// 会议室位置远程搜索相关状态
const locationOptions = ref<Array<{ label: string; value: string }>>([])
const locationLoading = ref(false)

// 会议室名称远程搜索相关状态
const roomNameOptions = ref<Array<{ label: string; value: string }>>([])
const roomNameLoading = ref(false)

/**
 * 远程搜索会议室位置
 * @param {string} query 用户输入
 */
const remoteLocationSearch = async (query: string) => {
  // 即使是空字符串也继续执行查询
  locationLoading.value = true

  try {
    // 调用后端接口获取位置列表，使用query参数而非路径参数
    const response = await request.get('/api/conferenceRoomManagement/location/list', {
      params: { text: query },
    })
    console.log('位置搜索原始响应:', response)

    // 直接硬编码处理，获取响应中可能包含的数据
    const rawData = (response as any).data?.result || (response as any).result || []
    console.log('位置原始数据:', rawData)

    // 确保是数组并转换为选项格式
    if (Array.isArray(rawData)) {
      locationOptions.value = rawData.map((item: any) => {
        // 如果已经是选项格式
        if (typeof item === 'object' && item !== null && 'label' in item && 'value' in item) {
          return { label: String(item.label), value: String(item.value) }
        }

        // 如果是字符串
        if (typeof item === 'string') {
          return { label: item, value: item }
        }

        // 如果是包含location的对象
        if (typeof item === 'object' && item !== null && 'location' in item) {
          const location = String(item.location)
          return { label: location, value: location }
        }

        // 其他情况
        const strValue = typeof item === 'object' ? JSON.stringify(item) : String(item)
        return { label: strValue, value: strValue }
      })

      console.log('处理后的位置选项:', locationOptions.value)
    } else {
      console.warn('位置数据不是数组')
      locationOptions.value = []
    }
  } catch (error) {
    console.error('获取位置列表失败:', error)
    locationOptions.value = []
  } finally {
    locationLoading.value = false
  }
}

/**
 * 远程搜索会议室名称
 * @param {string} query 用户输入
 */
const remoteRoomNameSearch = async (query: string) => {
  // 即使是空字符串也继续执行查询
  roomNameLoading.value = true

  try {
    // 使用会议室名称专用搜索接口，改为使用query参数
    const response = await request.get('/api/conferenceRoomManagement/roomName/list', {
      params: {
        text: query,
        location: searchParams.value.positionDescription || '',
      },
    })
    console.log('会议室名称搜索原始响应:', response)

    // 直接硬编码处理，获取响应中可能包含的数据
    const rawData = (response as any).data?.result || (response as any).result || []
    console.log('会议室名称原始数据:', rawData)

    // 确保是数组并转换为选项格式
    if (Array.isArray(rawData)) {
      roomNameOptions.value = rawData.map((item: any) => {
        // 如果已经是选项格式
        if (typeof item === 'object' && item !== null && 'label' in item && 'value' in item) {
          return { label: String(item.label), value: String(item.value) }
        }

        // 如果是字符串
        if (typeof item === 'string') {
          return { label: item, value: item }
        }

        // 优先使用roomName字段
        if (typeof item === 'object' && item !== null && 'roomName' in item) {
          return { label: String(item.roomName), value: String(item.roomName) }
        }

        // 其他情况
        const strValue = typeof item === 'object' ? JSON.stringify(item) : String(item)
        return { label: strValue, value: strValue }
      })

      console.log('处理后的会议室名称选项:', roomNameOptions.value)
    } else {
      console.warn('会议室名称数据不是数组')
      roomNameOptions.value = []
    }
  } catch (error) {
    console.error('获取会议室名称列表失败:', error)
    roomNameOptions.value = []
  } finally {
    roomNameLoading.value = false
  }
}

// 聚焦时加载位置数据
const handleLocationFocus = () => {
  remoteLocationSearch('')
}

// 聚焦时加载会议室名称数据
const handleRoomNameFocus = () => {
  remoteRoomNameSearch('')
}

// 使用计算属性创建搜索字段
const searchFieldsWithOptions = computed(() => {
  return searchFields.map((field) => {
    if (field.prop === 'positionDescription') {
      return {
        ...field,
        componentProps: {
          ...field.componentProps,
          filterable: true,
          remote: true,
          clearable: true,
          // @ts-ignore - 忽略类型检查
          remoteMethod: remoteLocationSearch,
          // @ts-ignore - 忽略类型检查
          loading: locationLoading.value,
          // @ts-ignore - 忽略类型检查
          options: locationOptions.value,
          // 使用focus事件名
          focus: handleLocationFocus,
        },
      }
    } else if (field.prop === 'roomName') {
      // 将roomName字段也改为select并支持远程搜索
      return {
        ...field,
        component: 'select', // 将input改为select
        componentProps: {
          ...field.componentProps,
          filterable: true,
          remote: true,
          clearable: true,
          // @ts-ignore - 忽略类型检查
          remoteMethod: remoteRoomNameSearch,
          // @ts-ignore - 忽略类型检查
          loading: roomNameLoading.value,
          // @ts-ignore - 忽略类型检查
          options: roomNameOptions.value,
          // 使用focus事件名
          focus: handleRoomNameFocus,
        },
      }
    }
    return field
  })
})

// 获取列表数据
const getList = async () => {
  try {
    tableState.loading = true
    const res = await getListApi({
      ...searchParams.value,
      page: page.value,
      limit: pageSize.value,
    })

    if (res?.result) {
      const { rows = [], count = 0 } = res.result
      tableState.data = rows
      tableState.pagination.total = count
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    tableState.loading = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getList()
}

// 重置
const handleReset = () => {
  searchParams.value = {
    roomName: '',
    status: '',
    positionDescription: '',
  }
  page.value = 1
  pageSize.value = 20
  getList()
}

// 分页变化
const handlePageChange = (newPage: number) => {
  page.value = newPage
  getList()
}

// 每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  page.value = 1
  getList()
}

// 初始化加载
onMounted(() => {
  try {
    // 使用修改后的搜索字段
    getList()
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败，请刷新页面重试')
  }
})

// 使用对话框Hook
const dialogState = reactive({
  visible: false,
  title: '新增会议室',
  formData: {} as MeetingRoomExtended,
  loading: false,
  confirmLoading: false,
  error: '',
})

// 是否为编辑模式
const isEditMode = ref(false)

// 详情弹窗相关
const detailDialogVisible = ref(false)
const currentDetail = ref<MeetingRoom | null>(null)

// 定义详情字段
const detailFields = [
  { label: '会议室名称', prop: 'roomName' },
  { label: '容纳人数', prop: 'capacity', render: (val: any) => `${val || 0}人` },
  { label: '面积', prop: 'area', render: (val: any) => `${val || 0}平方米` },
  { label: '位置描述', prop: 'positionDescription' },
  {
    label: '设备配置',
    prop: 'equipment',
    render: (val: any) => {
      if (!val) return '无'
      return val.split(',').filter(Boolean).join(', ')
    },
  },
  { label: '联系人', prop: 'linkman' },
  { label: '联系电话', prop: 'linkmanPhone' },
  { label: '预约规则', prop: 'reservationRule' },
  { label: '会议室描述', prop: 'description' },
  {
    label: '状态',
    prop: 'openStatus',
    render: (val: any) => val || '未设置',
  },
]

// 获取设备标签类型
const getEquipmentTagType = (equipment: string): 'success' | 'warning' | 'info' | 'primary' | 'danger' => {
  const typeMap: Record<string, 'success' | 'warning' | 'info' | 'primary' | 'danger'> = {
    投影仪: 'success',
    网络: 'info',
    电脑: 'warning',
    白板: 'primary',
    音响: 'danger',
    视频会议: 'success',
  }
  return typeMap[equipment] || 'primary'
}

// 获取状态标签类型
const getStatusTagType = (status: string): 'success' | 'warning' | 'info' | 'primary' | 'danger' => {
  const typeMap: Record<string, 'success' | 'warning' | 'info' | 'primary' | 'danger'> = {
    [ROOM_STATUS.UNOPEN]: 'info',
    [ROOM_STATUS.IDLE]: 'success',
  }
  return typeMap[status] || 'primary'
}

// 新增会议室
const handleAdd = () => {
  try {
    isEditMode.value = false
    dialogState.formData = {
      // 设置默认值
      equipment: [], // 设备配置初始为空数组
      openStatus: ROOM_STATUS.UNOPEN, // 默认设置为"未开放"状态
    } as unknown as MeetingRoomExtended
    dialogState.title = '新增会议室'
    dialogState.visible = true
  } catch (error) {
    console.error('打开新增弹窗失败:', error)
    ElMessage.error('操作失败')
  }
}

// 编辑会议室
const handleEdit = (row: MeetingRoom) => {
  try {
    isEditMode.value = true
    // 复制数据，并将equipment字符串转为数组
    const formData = { ...row } as MeetingRoomExtended

    // 处理设备配置字段，确保为数组形式
    if (typeof formData.equipment === 'string') {
      if (formData.equipment) {
        // 按逗号分割并过滤掉空值
        formData.equipment = formData.equipment.split(',').filter(Boolean)
      } else {
        // 如果为空字符串，设为空数组
        formData.equipment = []
      }
    } else if (!formData.equipment) {
      // 如果设备配置不存在，初始化为空数组
      formData.equipment = []
    }

    dialogState.formData = formData
    dialogState.title = '编辑会议室'
    dialogState.visible = true
  } catch (error) {
    console.error('打开编辑弹窗失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除会议室
const handleDelete = async (row: MeetingRoom) => {
  try {
    await ElMessageBox.confirm('确认删除该会议室吗？', '提示', {
      type: 'warning',
    })
    await delApi(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    console.error('删除会议室失败:', error)
  }
}

// 查看详情
const handleDetails = (row: MeetingRoom) => {
  try {
    // 先设置数据，再打开弹窗
    currentDetail.value = row
    // 打开详情弹窗
    detailDialogVisible.value = true
  } catch (error) {
    console.error('打开详情弹窗失败:', error)
    ElMessage.error('操作失败')
  }
}

// 详情弹窗关闭
const handleDetailClose = () => {
  try {
    // 先关闭弹窗
    detailDialogVisible.value = false
    // 延迟清除数据，避免闪烁
    setTimeout(() => {
      currentDetail.value = null
    }, 200)
  } catch (error) {
    console.error('关闭详情弹窗失败:', error)
  }
}

// 表单提交
const handleFormSubmit = async (formData: Record<string, any>) => {
  try {
    dialogState.confirmLoading = true

    // 使用表单组件提供的formData而不是dialogState中的数据
    const formDataCopy = { ...formData } as MeetingRoomExtended

    // 格式化数据（确保设备配置等字段正确处理）
    const formattedData = formatFormData(formDataCopy)

    if (isEditMode.value) {
      await editApi(formattedData as any)
      ElMessage.success('更新成功')
    } else {
      await addApi(formattedData as any)
      ElMessage.success('添加成功')
    }

    dialogState.visible = false
    getList()
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败')
  } finally {
    dialogState.confirmLoading = false
  }
}

// 表单取消
const handleFormCancel = () => {
  dialogState.visible = false
}

// 表单验证错误
const handleValidationError = (error: string) => {
  dialogState.error = error
}
</script>

<style scoped>
.no-background-container {
  min-height: 100vh;
  padding: 0 20px 20px;
  background-color: var(--el-bg-color);
}

.operations-container {
  display: flex;
  gap: 8px;
  white-space: nowrap;
}

.button-icon {
  margin-right: 4px;
  vertical-align: middle;
}

:deep(.el-tag) {
  margin-right: 5px;
  margin-bottom: 5px;
}

/* 设备配置下拉框样式 */
:deep(.equipment-select-dropdown) {
  min-width: 300px !important;
}

:deep(.el-select-dropdown__item) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-form-item__content .el-select .el-select__tags) {
  flex-wrap: wrap;
  height: auto;
}

/* 针对el-button的样式优化 */
:deep(.el-button--text) {
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
}

:deep(.el-button--text:hover) {
  background-color: var(--el-fill-color-light);
  transform: translateY(-1px);
}

:deep(.el-button--text.is-disabled) {
  opacity: 0.6;
}

/* 针对搜索表单的样式优化 */
:deep(.search-form-qvil) {
  margin-bottom: 0;
}

/* 表格行悬停效果优化 */
:deep(.el-table__row) {
  transition: all 0.15s;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-fill-color-lighter) !important;
}

/* 表格表头居中样式 */
:deep(.el-table__header th) {
  text-align: center;
}

/* 表格空数据样式 */
:deep(.el-table__empty-text) {
  padding: 40px 0;
  color: var(--el-text-color-secondary);
}

:deep(.el-pagination) {
  justify-content: flex-end;
  padding: 16px 0 0;
}
</style>
